package com.per.mybootall.test.testReflect;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2021/11/17
 * Time: 9:31
 * Description:通过反射替代switch，通过case对比的名字作为实现方法的名字，通过这种形式来替代switch
 */
@Component
public class Doing {
    @Autowired
    payImpl payImpl;

    //switch方式
    public void swtitchTest(String name,String money) {
        switch (name){
            case "aliPay":
                payImpl.aliPay();
                break;
            case "wechatPay":
                payImpl.wechatPay();
                break;
            case "bankPay":
                payImpl.bankPay(name,money);
                break;
        }


    }

    //反射的方式
    public void reflect(String name,String money)  {
        try{
            //获取class对象
            Class cla= Class.forName("com.per.mybootall.test.testReflect.payImpl");
            //通过class获取实例
            Object obj=cla.newInstance();
            //获取方法「方法名字，参数列表」
            Method method= cla.getDeclaredMethod(name,String.class,String.class);
            method.setAccessible(true);
            //调用方法
            method.invoke(obj,name,money);
        }catch (ClassNotFoundException | IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e){
            e.printStackTrace();
        }

    }
}
